package com.ccit.springbootlaw.mapper;

import com.ccit.springbootlaw.pojo.Subscription;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface SubscriptionMapper {
    // 根据ID查询权益包
    @Select("SELECT * FROM subscriptions WHERE id = #{id}")
    Subscription findById(int id);

    // 根据传入实体进行多条件查询的方法
    @Select("SELECT * FROM subscriptions WHERE " +
            "(#{subscription.type} IS NULL OR #{subscription.type} = '' OR type = #{subscription.type}) AND " +
            "(#{subscription.createdAt} IS NULL OR #{subscription.createdAt} = '' OR created_at = #{subscription.createdAt}) AND " +
            "(#{subscription.updatedAt} IS NULL OR #{subscription.updatedAt} = '' OR updated_at = #{subscription.updatedAt}) AND " +
            "(#{subscription.duration} IS NULL OR #{subscription.duration} = '' OR duration = #{subscription.duration})")
    List<Subscription> findBySubscriptionWithTypeNameLike(@Param("subscription") Subscription subscription);

    // 插入新的权益包
    @Insert("INSERT INTO subscriptions (type, created_at, updated_at, duration) VALUES (#{type}, NOW(), NOW(), #{duration})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertSubscription(Subscription subscription);

    // 更新权益包信息
    @Update("<script>" +
            "UPDATE subscriptions " +
            "<set>" +
            "<if test='type != null'>type = #{type},</if>" +
            "<if test='createdAt != null'>created_at = #{createdAt},</if>" +
            "<if test='duration != null'>duration = #{duration},</if>" +
            "updated_at = NOW()" +
            "</set>" +
            "WHERE id = #{id}" +
            "</script>")
    int updateSubscription(Subscription subscription);

    // 删除权益包
    @Delete("DELETE FROM subscriptions WHERE id = #{id}")
    int deleteSubscriptionById(int id);

    // 查询所有权益包
    @Select("SELECT * FROM subscriptions")
    List<Subscription> findAllSubscriptions();
}